import React, { useState } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  TextField,
  Button,
  Avatar,
  Grid,
  Alert,
  IconButton,
  useTheme
} from '@mui/material';
import { PhotoCamera as PhotoCameraIcon } from '@mui/icons-material';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../store';
import { updateUser } from '../../store/slices/authSlice';
import Loading from '../../components/common/Loading';

interface ProfileForm {
  username: string;
  email: string;
  bio: string;
}

const Profile: React.FC = () => {
  const { t } = useTranslation();
  const theme = useTheme();
  const dispatch = useDispatch();
  const { user } = useSelector((state: RootState) => state.auth);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<ProfileForm>({
    defaultValues: {
      username: user?.username || '',
      email: user?.email || '',
      bio: user?.bio || ''
    }
  });

  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      setAvatarFile(file);
      setPreviewUrl(URL.createObjectURL(file));
    }
  };

  const onSubmit = async (data: ProfileForm) => {
    try {
      setIsSubmitting(true);
      setError(null);
      
      // TODO: 实现头像上传和个人资料更新的API调用
      // const formData = new FormData();
      // if (avatarFile) {
      //   formData.append('avatar', avatarFile);
      // }
      // formData.append('username', data.username);
      // formData.append('email', data.email);
      // formData.append('bio', data.bio);

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));

      // 更新Redux状态
      dispatch(updateUser({
        ...user,
        ...data,
        avatar: previewUrl || user?.avatar
      }));

      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      setError(t('user.profile.error'));
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!user) {
    return <Loading />;
  }

  return (
    <Container maxWidth="md">
      <Typography variant="h4" component="h1" gutterBottom>
        {t('user.profile.title')}
      </Typography>

      <Paper elevation={3} sx={{ p: 3, mt: 4 }}>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 2 }}>
            {t('user.profile.success')}
          </Alert>
        )}

        <Box component="form" onSubmit={handleSubmit(onSubmit)}>
          <Grid container spacing={3}>
            <Grid item xs={12} display="flex" justifyContent="center">
              <Box sx={{ position: 'relative' }}>
                <Avatar
                  src={previewUrl || user.avatar}
                  sx={{
                    width: 120,
                    height: 120,
                    mb: 2,
                    bgcolor: theme.palette.primary.main
                  }}
                >
                  {user.username.charAt(0).toUpperCase()}
                </Avatar>
                <input
                  accept="image/*"
                  type="file"
                  id="avatar-upload"
                  onChange={handleAvatarChange}
                  style={{ display: 'none' }}
                />
                <label htmlFor="avatar-upload">
                  <IconButton
                    color="primary"
                    component="span"
                    sx={{
                      position: 'absolute',
                      bottom: 16,
                      right: 0,
                      bgcolor: 'background.paper'
                    }}
                  >
                    <PhotoCameraIcon />
                  </IconButton>
                </label>
              </Box>
            </Grid>

            <Grid item xs={12}>
              <TextField
                fullWidth
                label={t('user.profile.username')}
                error={!!errors.username}
                helperText={errors.username?.message}
                {...register('username', {
                  required: t('user.profile.usernameRequired'),
                  minLength: {
                    value: 3,
                    message: t('user.profile.usernameMinLength')
                  },
                  pattern: {
                    value: /^[a-zA-Z0-9_-]+$/,
                    message: t('user.profile.usernamePattern')
                  }
                })}
              />
            </Grid>

            <Grid item xs={12}>
              <TextField
                fullWidth
                label={t('user.profile.email')}
                error={!!errors.email}
                helperText={errors.email?.message}
                {...register('email', {
                  required: t('user.profile.emailRequired'),
                  pattern: {
                    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                    message: t('user.profile.emailInvalid')
                  }
                })}
              />
            </Grid>

            <Grid item xs={12}>
              <TextField
                fullWidth
                multiline
                rows={4}
                label={t('user.profile.bio')}
                error={!!errors.bio}
                helperText={errors.bio?.message}
                {...register('bio')}
              />
            </Grid>

            <Grid item xs={12}>
              <Button
                type="submit"
                variant="contained"
                color="primary"
                disabled={isSubmitting}
              >
                {t('user.profile.save')}
              </Button>
            </Grid>
          </Grid>
        </Box>
      </Paper>
    </Container>
  );
};

export default Profile; 